<?php
class Yamarket_OffersController extends Zend_Rest_Controller {
	public function init() {
		$this->mapper = new Yamarket_Model_OffersMapper( );
	}
    
	public function indexAction() {
        $start =(int) $this->_request->getParam('start',0);
        $limit =(int) $this->_request->getParam('limit',25);
        $query = $this->_request->getParam('query',null);
        if (null!=$query){
            $filterChain = new Zend_Filter ( );
            $query = $filterChain    ->addFilter ( new Zend_Filter_StripTags ( ) )
                            ->addFilter ( new Zend_Filter_StringTrim ( ) )
                            ->filter ( $query );
        }
		$result ['data'] = $this->mapper->fetchAll($query,$start,$limit);
        $result ['total'] = $this->mapper->count();
		$this->_helper->json ( $result );
	}
	public function getAction() {
		$this->_helper->viewRenderer->setRender('editor-js');
		$this->_helper->layout()->disableLayout();
	}
	public function postAction() {
        $request = $this->getRequest();
        $params = Zend_Json::decode ( $request->getRawBody () );
        $f = new Yamarket_Form_OffersNew();
        if (!$f->IsValid($params['data']))
            throw new Zend_Exception("Invalid post data");
        $params = $f->getValidValues($params['data']);
        $t_mapper = new Admin_Model_TreeNodeMapper();
        $node = $t_mapper->find($params['NodeId']);
        $offer = new Yamarket_Model_Offer($params);
        $offer->setPublish(0)
                ->setCurrencyId('RUR')
                ->setPrice($this->_getPrice($node))
                ->setModel($this->_getModel($node))
                ->setVendor($this->_getVendor($node))
                ->setDescription($this->_getDescription($node))
                ->setManufacturerWarranty(1);
        $f2 = new Yamarket_Form_Offers();
        $params = $f2->getValidValues($offer->toArray());
        try{
            $offer->setId($this->mapper->save($params));
            $params['Id'] = $offer->getId();
            $result ['data'] = $params;
            $result ['success'] = true;
        }
        catch(Exception $e)
        {
            $result ['success'] = false;
            throw $e;
        }
        $this->_helper->json ( $result );
	}
	public function putAction() {
        $request = $this->getRequest();
		$params = Zend_Json::decode ( $request->getRawBody () );
        $f = new Yamarket_Form_Offers();
        /*if (!$f->IsValid($params['data']))
            throw new Zend_Exception("Invalid put data");*/ //всё не проверяем, т.к. данные приходят не целиком
        $params = $f->getValidValues($params['data']);
        try{
            $this->mapper->save($params);
            $result ['success'] = true;
        }
        catch(Exception $e)
        {
            $result ['success'] = false;
        }
        $this->_helper->json ( $result );
	}
	
	public function deleteAction() {
		$request = $this->getRequest();
        $id = $request->getParam ( 'id', 0 );
        if ($id<1) {
            $this->_helper->json ( array('success'=>false, 'msg'=>'No Id'));
            return;
        }
        try{
            $this->mapper->delete($id);
            $this->_helper->json(array('success'=>true));
        }
        catch(Exception $e)
        {
            $this->_helper->json(array('success'=>false));
        }
	}

    
    private function _getPrice($node){
        return method_exists($node,'getPrice')?$node->getPrice():0;
    }
    private function _getDescription($node){
        return method_exists($node,'getShortDescription')?$node->getShortDescription():
            (method_exists($node,'getDescription')?$node->getDescription():"");
    }
    private function _getModel($node){
        return method_exists($node,'getModel')?$node->getModel():$node->getName();
    }
    private function _getVendor($node){
        return method_exists($node,'getVendore')?$node->getVendore():"";
    }
}

